var express = require('express');
var router = express.Router();
var Article = require('./models');
var Message = require('./message');

/* GET home page. */
router.get('/',async function(req, res, next) {
  //文章
  const list = await Article.find().sort({"_id":-1});
  //留言
  const msList = await Message.find().sort({"_id": -1});
  res.locals.user = req.session.user || "";
  res.locals.message = req.session.message || "";
  res.render('index', {list, msList});
});

//打开创建文章页面
router.get("/create", function(req, res) {
    return res.render("create");
})

//创建文章方法
router.post("/create",async function (req, res) {
     const {title, body} = req.body;
     const doc = new Article({
         title,
         body,
         createTime: new Date(),
         updateTime: new Date()
     });
     await doc.save();
     return res.redirect("/");
})

//打开编辑文章页面
router.get("/:id/edit",async function(req , res){
   const id = req.params.id;
    const doc = await Article.findById(id);
    return res.render("edit",{doc});
})

//更新文章方法
router.post("/update/:id", async function (req, res) {
  const id = req.params.id;
  const {title, body} = req.body;
  const doc = await Article.findById(id);
  if(doc){
    doc.title = title;
    doc.body = body;
    await doc.save();
  }

  return res.redirect("/");
})

//删除文章方法
router.get("/:id/delete",async function (req, res) {
     await Article.remove({_id:req.params.id});
     return res.redirect("/");
})

module.exports = router;
